package com.rxw.nutmall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.rxw.nutmall.page.PageData;
import com.rxw.nutmall.product.entity.CategoryBrandRelation;
import com.rxw.nutmall.product.mapper.CategoryBrandRelationMapper;
import com.rxw.nutmall.product.service.CategoryBrandRelationService;
import com.rxw.nutmall.service.impl.BaseServiceImpl;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 品牌分类关联 服务实现类
 * </p>
 *
 * @author 咸蛋超人
 * @since 2024-01-04
 */
@Service
public class CategoryBrandRelationServiceImpl extends BaseServiceImpl<CategoryBrandRelationMapper, CategoryBrandRelation> implements CategoryBrandRelationService {

    @Override
    public PageData<CategoryBrandRelation> page(Map<String, Object> params) {
        IPage<CategoryBrandRelation> page = baseDao.selectPage(
                getPage(params, "", true),
                getWrapper(params)
        );
        return getPageData(page, CategoryBrandRelation.class);
    }

    @Override
    public CategoryBrandRelation get(Long id) {
        return baseDao.selectById(id);
    }

    @Override
    public List<CategoryBrandRelation> getList(CategoryBrandRelation dto) {
        QueryWrapper<CategoryBrandRelation> wrapper = new QueryWrapper<>();
        return baseDao.selectList(wrapper);
    }

    @Override
    public String save(CategoryBrandRelation dto) {
        insert(dto);
        return dto.getId().toString();
    }

    @Override
    public void saveList(List<CategoryBrandRelation> list) {
        insertBatch(list);
    }

    @Override
    public void update(CategoryBrandRelation dto) {
        updateById(dto);
    }

    @Override
    public void updateList(List<CategoryBrandRelation> list) {
        updateBatchById(list);
    }

    @Override
    public void remove(Long id) {
        deleteById(id);
    }

    @Override
    public void removeList(List<Long> idList) {
        deleteBatchIds(idList);
    }

    @SneakyThrows
    private QueryWrapper<CategoryBrandRelation> getWrapper(Map<String, Object> params) {
        QueryWrapper<CategoryBrandRelation> wrapper = new QueryWrapper<>();
        for (String key : params.keySet()) {
            Field[] fields = CategoryBrandRelation.class.getDeclaredFields();
            boolean b = Arrays.stream(fields).anyMatch(field -> field.getName().equals(key));
            if (b) {
                Field field = CategoryBrandRelation.class.getDeclaredField(key);
                Class<?> type = field.getType();
                String fieldUnderline = StringUtils.capitalize(key);
                Object value = params.get(key);
                wrapper.eq(fieldUnderline, type.cast(value));
            }
        }
        return wrapper;
    }
}
